package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        List<Element> allList = rootElement.selectNodes("//insert");
        allList.addAll(rootElement.selectNodes("//update"));
        allList.addAll(rootElement.selectNodes("//delete"));
        allList.addAll(rootElement.selectNodes("//select"));
        String id;
        String resultType;
        String paramterType;
        String sqlText;
        MappedStatement mappedStatement;
        String key;
        for (Element element : allList) {
            id = element.attributeValue("id");
            resultType = element.attributeValue("resultType");
            paramterType = element.attributeValue("paramterType");
            sqlText = element.getTextTrim();
            mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
            System.out.println(mappedStatement);
        }
        System.out.println(configuration.getMappedStatementMap());
    }

}
